﻿using ConsoleTables;
using InfluxData.Net.Common.Enums;
using InfluxData.Net.InfluxDb;
using InfluxData.Net.InfluxDb.Models;
using InfluxData.Net.InfluxDb.Models.Responses;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client;
using CRL.Core;
using Newtonsoft.Json.Linq;
using InfluxDB.Client.Core;
using InfluxDB.Client.Linq;
using Measurement = InfluxDB.Client.Core.Measurement;
namespace testInfluxDB
{

    public class testv2
    {
        static string infuxUrl = "http://localhost:8086/";
       
        const string bucket = "request2024";
        const string org = "default";
        const string token = "2aLXyIyfvpxMTFm5vTpZ3o6MebF4XiYNjq_5H41hkA-xFHX-fNdD-SEeR-EeTQbXUpJ2SDHOt47kRs8NkwO6YA==";
        //https://github.com/tihomir-kit/InfluxData.Net
        static InfluxDBClient client;
        static WriteApi writeApi;
        static testv2()
        {
            client = new InfluxDBClient(infuxUrl, token);
            writeApi = client.GetWriteApi();
            new ThreadWork().Start("222", () =>
            {
                testInsert2Base();
                return true;
            }, 5);
        }

        static void testInsert2Base()
        {
            var dto = new requestInfo { projectName = "projectName1", requestPath = "/home/index", responseCode = "200", time = DateTime.UtcNow, requestElMs = 10 };
            writeApi.WriteMeasurement(dto, WritePrecision.Ns, bucket, org);
        }
        public static async void testQuery2()
        {
            var queryApi = client.GetQueryApi();

            // 使用 Flux 查询语句进行分组
            string fluxQuery = @"
from(bucket: ""request2024"")
  |> range(start: -5m)
  |> filter(fn: (r) => r._measurement == ""requestInfo"")
  |> aggregateWindow(every: 10s, fn: count, createEmpty: false)
";
            var result = await queryApi.QueryAsync(fluxQuery, org);

            // 处理查询结果
            foreach (var table in result)
            {
                foreach (var record in table.Records)
                {
                    Console.WriteLine($"Tag Name: {record.GetValue()}, Mean Value: {record.Row}");
                }
            }
        }
        //static void testQuery3()
        //{
        //    var client = new InfluxDBClient(infuxUrl, token);
        //    var query = from s in InfluxDBQueryable<requestInfo>.Queryable(bucket,org, client.GetQueryApiSync())
        //                //where s.time.AggregateWindow(TimeSpan.FromDays(4), null, "mean")
        //                select s;

        //    var sensors = query.ToList();
        //}
    }
}